"""用户仓库类"""

from typing import Optional, List
from sqlalchemy.orm import Session
from sqlalchemy import and_, or_
from .base import BaseRepository
from app.models.database.user import User
import uuid


class UserRepository(BaseRepository[User]):
    """用户数据访问仓库"""
    
    def __init__(self, db: Session):
        super().__init__(db, User)
    
    def create_user(self, user_id: Optional[str] = None, username: Optional[str] = None, 
                   email: str = "", password_hash: str = "") -> User:
        """创建新用户"""
        return self.create(
            user_id=user_id or str(uuid.uuid4()),
            username=username,
            email=email,
            password_hash=password_hash,
            is_active="true"
        )
    
    def get_by_user_id(self, user_id: str) -> Optional[User]:
        """根据user_id获取用户"""
        return self.get_one_by_filter(user_id=user_id)
    
    def get_by_email(self, email: str) -> Optional[User]:
        """根据邮箱获取用户"""
        return self.get_one_by_filter(email=email)
    
    def get_by_username(self, username: str) -> Optional[User]:
        """根据用户名获取用户"""
        return self.get_one_by_filter(username=username)
    
    def get_active_users(self, skip: int = 0, limit: int = 100) -> List[User]:
        """获取活跃用户列表"""
        return self.get_by_filter(is_active="true")
    
    def search_users(self, query: str, skip: int = 0, limit: int = 100) -> List[User]:
        """搜索用户"""
        return (
            self.db.query(User)
            .filter(
                or_(
                    User.username.ilike(f"%{query}%"),
                    User.email.ilike(f"%{query}%")
                )
            )
            .offset(skip)
            .limit(limit)
            .all()
        )
    
    def update_user_emotion(self, user_id: str, emotion: str) -> Optional[User]:
        """更新用户情绪"""
        user = self.get_by_user_id(user_id)
        if user:
            user.update_emotion(emotion)
            self.db.commit()
            self.db.refresh(user)
            return user
        return None
    
    def activate_user(self, user_id: str) -> Optional[User]:
        """激活用户"""
        user = self.get_by_user_id(user_id)
        if user:
            return self.update(user, is_active="true")
        return None
    
    def deactivate_user(self, user_id: str) -> Optional[User]:
        """停用用户"""
        user = self.get_by_user_id(user_id)
        if user:
            return self.update(user, is_active="false")
        return None
    
    def update_last_login(self, user_id: str) -> Optional[User]:
        """更新最后登录时间"""
        from datetime import datetime
        user = self.get_by_user_id(user_id)
        if user:
            return self.update(user, last_login_at=datetime.utcnow())
        return None
    
    def get_users_by_emotion(self, emotion: str) -> List[User]:
        """根据情绪获取用户"""
        return self.get_by_filter(current_emotion=emotion)
    
    def get_users_with_recent_activity(self, days: int = 7) -> List[User]:
        """获取最近活跃的用户"""
        from datetime import datetime, timedelta
        cutoff_date = datetime.utcnow() - timedelta(days=days)
        
        return (
            self.db.query(User)
            .filter(
                and_(
                    User.is_active == "true",
                    User.last_login_at >= cutoff_date
                )
            )
            .all()
        )
    
    def check_email_exists(self, email: str) -> bool:
        """检查邮箱是否已存在"""
        return self.exists(email=email)
    
    def check_username_exists(self, username: str) -> bool:
        """检查用户名是否已存在"""
        return self.exists(username=username)
    
    def check_user_id_exists(self, user_id: str) -> bool:
        """检查用户ID是否已存在"""
        return self.exists(user_id=user_id)
    
    def get_user_stats(self, user_id: str) -> dict:
        """获取用户统计信息"""
        user = self.get_by_user_id(user_id)
        if not user:
            return {}
        
        # 这里可以添加更多统计逻辑
        # 比如统计对话数量、消息数量等
        return {
            "user_id": user.user_id,
            "username": user.username,
            "email": user.email,
            "is_active": user.is_user_active(),
            "current_emotion": user.current_emotion,
            "emotion_history_count": len(user.emotion_history) if user.emotion_history else 0,
            "created_at": user.created_at.isoformat() if user.created_at else None,
            "last_login_at": user.last_login_at.isoformat() if user.last_login_at else None
        }
    
    def get_emotion_statistics(self) -> dict:
        """获取情绪统计"""
        # 统计各种情绪的用户数量
        emotions = {}
        users = self.get_active_users()
        
        for user in users:
            if user.current_emotion:
                emotions[user.current_emotion] = emotions.get(user.current_emotion, 0) + 1
        
        return emotions
